//
//  AppDelegate.m
//  PosApp
//
//  Created by 刘萍 on 2018/8/31.
//  Copyright © 2018年 李英新. All rights reserved.
//

#import "AppDelegate.h"
#import "BeginViewController.h"
#import "MainTabbarController.h"
#import "MainNavigationController.h"
#import "LoginViewController.h"
#import "RouterManager.h"
#import <Bugly/Bugly.h>


#import "PosApp-Swift.h"


@interface AppDelegate ()<selectDelegate,WXApiDelegate,BuglyDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    //极光相关
    //notice: 3.0.0 及以后版本注册可以这样写，也可以继续用之前的注册方式
//    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
//    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionSound;
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//        // 可以添加自定义 categories
//        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
//        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
//    }
//    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
//
//    // init Push
//    [JPUSHService setupWithOption:launchOptions appKey:@"e446d6d693c4b3889eb1120a"
//                          channel:@"App Store"
//                 apsForProduction:0
//            advertisingIdentifier:nil];
    
//    启动页
    NSArray *images = @[@"BeginImage01", @"BeginImage02", @"BeginImage03"];
    if ([[[BeginViewController alloc] init] isShow]) {
        self.window.rootViewController = [BeginViewController shareXTGuideVC];
        [[BeginViewController shareXTGuideVC] initWithXTGuideView:images];
        [BeginViewController shareXTGuideVC].delegate = self;
    }else{
        [self click];
    }
    
    [self.window makeKeyAndVisible];
    
    //腾讯登陆 分享
    TencentOAuth * ten = [[TencentOAuth alloc] initWithAppId:KQQAppID andDelegate:nil];
    NSLog(@"----%@",ten.appId);
    //微信
    [WXApi registerApp:KWXAppID enableMTA:YES];
    
    BuglyConfig * config = [[BuglyConfig alloc] init];
    config.debugMode = YES;
    config.blockMonitorEnable = YES;
    config.blockMonitorTimeout = 1.5;
    config.channel = @"Bugly";
    config.delegate = self;
    config.consolelogEnable = NO;
    config.viewControllerTrackingEnable = NO;
    
    [Bugly startWithAppId:@"0baa1ea996"
#if DEBUG
        developmentDevice:YES
#endif
                   config:config];
    
    [Bugly setUserIdentifier:[NSString stringWithFormat:@"User: %@", [UIDevice currentDevice].name]];
    
    [Bugly setUserValue:[NSProcessInfo processInfo].processName forKey:@"Process"];
    
    
    return YES;
}

- (void)click{
    if (KIsLogin) {
        [AppContext.shared queryLocalInfo];
        
        
        MainTabbarController * tabC = [[MainTabbarController alloc] init];
        self.window.rootViewController = tabC;
    }else{
        LoginViewController * loginC = [[LoginViewController alloc] init];
        MainNavigationController * nac = [[MainNavigationController alloc] initWithRootViewController:loginC];
        self.window.rootViewController = nac;
    }
}


- (NSString * BLY_NULLABLE)attachmentForException:(NSException * BLY_NULLABLE)exception{
    
    return @"This is an attachment";
}

//极光相关
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
//    [JPUSHService registerDeviceToken:deviceToken];
    
}
#pragma mark- JPUSHRegisterDelegate

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//
//    // Required, iOS 7 Support
//    [JPUSHService handleRemoteNotification:userInfo];
//    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
//    [JPUSHService handleRemoteNotification:userInfo];
}


//微信 QQ 相关回调
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}


//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
//
//    if ([url.host isEqualToString:@"safepay"]) {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//            NSLog(@"result = %@",resultDic);
//            NSString * AliStr = resultDic[@"resultStatus"];
//            if ([AliStr isEqual:@"9000"]) {
//                //支付成功
//                [MBProgressHUD showAlertViewWithText:@"支付成功"];
//
//                [[NSNotificationCenter defaultCenter]postNotificationName:[RouterManager alipaySuccessNotificationName] object:nil];
////                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipaySuccess" object:nil];
//            }else{
//                //支付失败
//                [MBProgressHUD showAlertViewWithText:resultDic[@"memo"]];
////                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipayFaild" object:nil];
//            }
//        }];
//        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"== %@",resultDic);
//            NSString * AliStr = resultDic[@"resultStatus"];
//            NSString *result = resultDic[@"result"];
//            if ([AliStr isEqual:@"9000"]) {
//                [self TurehandlderAliPayAuthInfo:result];
//            }
//
//        }];
//        return YES;
//    }else if ([url.host isEqual:@"response_from_qq"]) {
//        return [TencentOAuth HandleOpenURL:url];
//    }else{
//        return [WXApi handleOpenURL:url delegate:self];
//    }
//}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options {
    
    NSLog(@"callback url:%@",url);
    NSLog(@"callback url:%@",url.host);

    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            NSLog(@"result = %@",resultDic);
            NSString * AliStr = resultDic[@"resultStatus"];
            if ([AliStr isEqual:@"9000"]) {
                //支付成功
                [MBProgressHUD showAlertViewWithText:@"支付成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipaySuccess" object:nil];
            }else{
                //支付失败
                [MBProgressHUD showAlertViewWithText:resultDic[@"memo"]];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipayFaild" object:nil];
            }
        }];
        
        
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"== %@",resultDic);
            
            NSString * AliStr = resultDic[@"resultStatus"];
            NSString *result = resultDic[@"result"];
            if ([AliStr isEqual:@"9000"]) {
                [self TurehandlderAliPayAuthInfo:result];
            }
            
        }];
        return YES;
    }else if ([url.host isEqual:@"response_from_qq"]) {
        return [TencentOAuth HandleOpenURL:url];
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    
}


- (void)TurehandlderAliPayAuthInfo:(NSString *)result{
    
    NSLog(@"diaoyong e %@",result);
    
    NSString *authCode = nil;
    NSString *openId = nil;
    NSString *UserID = nil;
    
    if (result.length > 0) {
        NSArray *resultArr = [result componentsSeparatedByString:@"&"];
        for (NSString *subResult in resultArr) {
            if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                authCode = [subResult substringFromIndex:10];
                
            }
            if (subResult.length > 32 && [subResult hasPrefix:@"alipay_open_id="]) {
                openId = [subResult substringFromIndex:15];
            }
            
            if (subResult.length > 16 && [subResult hasPrefix:@"user_id="]) {
                UserID = [subResult substringFromIndex:8];
                
                NSLog(@"授权结果 authCode = %@, openId = %@, userID = %@", authCode?:@"", openId?:@"", UserID?:@"");
                
                NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
                [dic setObject:KUseriPhone forKey:@"phone"];
                [dic setObject:UserID forKey:@"auth_code"];
                [dic setObject:@"Alipay" forKey:@"account_type"];
                
                [MainObjectWay PostWithMethod:@"account_bind" andAction:@"User" andAddParam:YES parameters:dic success:^(id responseObject) {
                    
                    NSLog(@"绑定结果 = %@",responseObject);
                    NSLog(@"绑定结果信息 = %@",responseObject[@"msg"]);
                    
                    if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
                        [_AliPaydelegate handlderAliPayAuthInfo:nil];
                    }else{
                        [MBProgressHUD showAlertViewWithText:@"授权失败"];
                    }
                    
                } failure:^(NSError *error) {
                    NSLog(@"错误信息 = %@",error);
                }];
               
            }
        }
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"PosApp"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
